import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue2'
import vueJsx from '@vitejs/plugin-vue2-jsx'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { viteMockServe } from 'vite-plugin-mock'
// https://github.com/vitejs/vite/tree/main/packages/plugin-legacy
import legacy from '@vitejs/plugin-legacy'

import { loadEnv } from 'vite'
import { wrapperEnv } from './build/utils'
import path from 'path'

function resolve(dir) {
  return path.resolve(process.cwd(), '.', dir)
}

export default defineConfig(({ command, mode }) => {
  // command === 'serve' | 'build'
  // mode === 'development' | 'production'

  const root = process.cwd()

  const env = loadEnv(mode, root)

  // The boolean type read by loadEnv is a string. This function can be converted to boolean type
  const viteEnv = wrapperEnv(env)

  const { VITE_PUBLIC_PATH, VITE_DEV_PORT, VITE_BASEURL, VITE_PROD_MOCK } = viteEnv

  return {
    base: VITE_PUBLIC_PATH,
    root,
    plugins: [
      vue(),
      vueJsx(),
      legacy({
        // Default: 'last 2 versions and not dead, > 0.3%, Firefox ESR'
        targets: ['defaults', 'not IE 11'],
      }),
      createSvgIconsPlugin({
        // 指定要缓存的图标文件夹
        iconDirs: [resolve('src/icons/svg')],
        // 执行icon name的格式
        symbolId: 'icon-[dir]-[name]',
      }),
      viteMockServe({
        mockPath: 'mock',
        localEnabled: command === 'serve',
        prodEnabled: command !== 'serve' && VITE_PROD_MOCK,
        // 这样可以控制关闭mock的时候不让mock打包到最终代码内，注意引入的路径是基于main.js文件的位置，不是根目录
        injectCode: `
          import { setupProdMockServer } from '../mock/mockProdServer';
          setupProdMockServer();
        `
      })
    ],
    // optimizeDeps: {
    // },
    resolve: {
      alias: {
        '@': resolve('src') + '/',
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          // additionalData: `
          //   @import '@/styles/index.scss';
          // `
        }
      }
    },
    server: {
      port: VITE_DEV_PORT,
      host: true,
      open: true,
      // proxy: {
      //   '/vue-admin-template': {
      //     target: `http://127.0.0.1:${VITE_DEV_PORT}`,
      //     changeOrigin: true,
      //     rewrite: (path) => path.replace(/^\/vue-admin-template/, '/api')
      //   },
      // }
    },
  }
})
